package com.distribute.config;

import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.distribute.common.utils.JsonUtil;
import com.distribute.dto.LoginUser;
import com.distribute.entity.TSysAcl;
import com.distribute.entity.TSysUser;
import com.distribute.enums.UserStatus;
import com.distribute.service.SysAclService;
import com.distribute.service.UserService;


@Service
public class UserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private UserService userService;
	@Autowired
	private SysAclService sysAclService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		TSysUser sysUser = userService.getByName(username);
		if (sysUser == null) {
			throw new AuthenticationCredentialsNotFoundException("用户名不存在");
		} else if (sysUser.getStatus() == UserStatus.LOCKED.getCode()) {
			throw new LockedException("用户被锁定,请联系管理员");
		} else if (sysUser.getStatus() == UserStatus.DISABLED.getCode()) {
			throw new DisabledException("用户已作废");
		}

		LoginUser loginUser = new LoginUser();
		BeanUtils.copyProperties(sysUser, loginUser);
		List<TSysAcl> aclList = sysAclService.listByUserId(sysUser.getId());
		if (CollectionUtils.isNotEmpty(aclList)) {
			aclList = aclList.stream().filter(p -> StringUtils.isNotBlank(p.getPermission()))
					.collect(Collectors.toList());
		}
		loginUser.setSysAcls(aclList);
		String obj2String = JsonUtil.obj2String(loginUser);
		System.out.println(obj2String);
		return loginUser;
	}

}
